package filter;

import pojo.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "LoginFilter", urlPatterns = {"/*"}, initParams = {
        @WebInitParam(name = "encoding", value = "UTF-8")
})
public class LoginFilter implements Filter {
    // 过滤中文乱码的编码方式
    private String encoding = "UTF-8";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 从 web.xml 中获取编码配置，如果没有则使用默认的 UTF-8
        String encodingParam = filterConfig.getInitParameter("encoding");
        if (encodingParam != null) {
            encoding = encodingParam;
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        String requestURI = httpServletRequest.getRequestURI();

        // 设置编码：如果是JSON请求，确保编码为UTF-8
        if (httpServletRequest.getContentType() != null &&
                httpServletRequest.getContentType().contains("application/json")) {
            // 处理JSON请求的编码
            httpServletRequest.setCharacterEncoding(encoding);
            httpServletResponse.setCharacterEncoding(encoding);
            httpServletResponse.setContentType("application/json;charset=" + encoding);
        } else if (httpServletRequest.getContentType() != null &&
                httpServletRequest.getContentType().contains("multipart/form-data")) {
            // 对于文件上传表单，保持默认处理
            // (通常上传的表单会直接由服务器处理，编码不需要手动设置)
            httpServletRequest.setCharacterEncoding(encoding);
            httpServletResponse.setCharacterEncoding(encoding);
        } else {
            // 默认情况下，处理其他请求（例如 HTML 页面）
            httpServletRequest.setCharacterEncoding(encoding);
            httpServletResponse.setCharacterEncoding(encoding);
            httpServletResponse.setContentType("text/html;charset=" + encoding);
        }

        // 获取会话
        HttpSession session = httpServletRequest.getSession(false);
        String loginURI = httpServletRequest.getContextPath() + "/index.jsp";

        /*
        if (requestURI.endsWith("/index.jsp") || requestURI.endsWith("/user/login.jsp") ||
                requestURI.endsWith("/user/register.jsp") || requestURI.equals("http://localhost:8180")) {
            // 首页、登录、注册等页面可以访问
            chain.doFilter(request, response);
        }
         */
        // 下面过滤界面
        boolean loggedIn = false;
        if (requestURI.contains("/admin")) {
            // 管理员相关界面需要登录

            if (session != null) {
                User user = (User) session.getAttribute("user");
                loggedIn = (user != null && user.getStatus().equals("2"));
            }

            if (!loggedIn) {
                // 用户未登录，输出一段 JavaScript 代码弹出提示框，并且可以设置点击确定之后自动跳转到首页的时间
                httpServletResponse.getWriter().println("<script>alert('请先登录！'); setTimeout(function() { window.location.href='" + loginURI + "'; }, 1);</script>");
            } else {
                // 用户已登录，继续处理请求
                chain.doFilter(request, response);
            }
        } else if (requestURI.endsWith("/personalCenter.jsp")) {

            if (session != null) {
                User user = (User) session.getAttribute("user");
                loggedIn = (user != null);
            }
            if (!loggedIn) {
                // 用户未登录，输出一段 JavaScript 代码弹出提示框，并且可以设置点击确定之后自动跳转到首页的时间
                httpServletResponse.getWriter().println("<script>alert('请先登录！'); setTimeout(function() { window.location.href='" + loginURI + "'; }, 1);</script>");
            } else {
                // 用户已登录，继续处理请求
                chain.doFilter(request, response);
            }
        } else if (requestURI.contains("/musicBoxes") || requestURI.contains("/playlists")) {
            if (session != null) {
                User user = (User) session.getAttribute("user");
                loggedIn = (user != null);
            }
            if (!loggedIn) {
                // 用户未登录，输出一段 JavaScript 代码弹出提示框，并且可以设置点击确定之后自动跳转到首页的时间
                httpServletResponse.getWriter().println("<script>alert('请先登录！'); setTimeout(function() { window.location.href='" + loginURI + "'; }, 1);</script>");
            } else {
                // 用户已登录，继续处理请求
                chain.doFilter(request, response);
            }
        }
        else {
            // 其他普通页面，允许访问
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {
        // 释放资源，这里暂时不需要做什么
    }
}
